
from datetime import timedelta

from fastapi import APIRouter
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_amis_admin.globals.deps import SyncSess

from .service import Token, authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, \
    get_current_active_user
from backend.apps.security.models import SecurityUser

router = APIRouter()

@router.post("/token")
async def login_for_access_token(sses: SyncSess,
        form_data: OAuth2PasswordRequestForm = Depends(),
) -> Token:
    user = authenticate_user(sses, form_data.username, form_data.password)
    print(user)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return Token(access_token=access_token, token_type="bearer")

@router.get("/me", response_model=SecurityUser)
async def read_users_me(current_user: SecurityUser = Depends(get_current_active_user)):
    return current_user

